package com.mac.hosp_pre.admin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.Week;
import com.mac.hosp_pre.admin.dto.ScheduleOrderRespDto;
import com.mac.hosp_pre.admin.entity.PreBookRule;
import com.mac.hosp_pre.admin.entity.Schedule;
import com.mac.hosp_pre.admin.model.req.ScheduleQueryReqDto;
import com.mac.hosp_pre.admin.model.req.ScheduleReqDto;
import com.mac.hosp_pre.admin.model.resp.*;
import com.mac.hosp_pre.admin.service.DepartmentService;
import com.mac.hosp_pre.admin.service.HospitalService;
import com.mac.hosp_pre.admin.service.ScheduleService;
import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.except.ServiceException;
import com.mac.hosp_pre.reply.PageResult;
import com.mac.hosp_pre.util.date.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ScheduleServiceImpl extends BaseMongoServiceImpl<Schedule> implements ScheduleService {

    @Autowired
    private HospitalService hospitalService;
    @Autowired
    private DepartmentService departmentService;

    @Override
    public void add(ScheduleReqDto req) {
        //根据医院编号 和 排班编号查询
        if (StringUtils.isAnyBlank(req.getHospCode(),req.getHospScheduleId())){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和排班ID不能为空");
        }
        Schedule schedule = new Schedule();
        schedule.setHospCode(req.getHospCode());
        schedule.setHospScheduleId(req.getHospScheduleId());
        Schedule scheduleExist = super.findOne(schedule);
        //判断
        if(Objects.nonNull(scheduleExist)) {
            scheduleExist.setUpdateTime(new Date());
            scheduleExist.setDeleted(false);
            scheduleExist.setStatus(1);
            super.updateById(scheduleExist.getId(),scheduleExist);
        } else {
            Schedule entity = new Schedule();
            BeanUtils.copyProperties(req,entity);
            Date date = new Date();
            entity.setCreateTime(date);
            entity.setUpdateTime(date);
            entity.setDeleted(false);
            entity.setStatus(1);
            super.save(entity);
        }
    }

    @Override
    public PageResult<ScheduleRespDto> findPageSchedule(ScheduleQueryReqDto scheduleQuery) {
        // 创建Pageable对象，设置当前页和每页记录数
        PageRequest pageable = PageRequest.of(scheduleQuery.getPageNo() - 1,scheduleQuery.getPageSize(), Sort.by(Sort.Direction.DESC,"updateTime"));
        // 创建Example对象
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(scheduleQuery,schedule);
        PageResult<Schedule> pageResult = super.findPageByCondition(pageable, schedule);
        if (CollectionUtil.isNotEmpty(pageResult.getList())){
            List<ScheduleRespDto> respDtoList = pageResult.getList().stream().map(item -> {
                ScheduleRespDto respDto = new ScheduleRespDto();
                BeanUtils.copyProperties(item,respDto);
                return respDto;
            }).collect(Collectors.toList());
            return new PageResult<>(respDtoList,pageResult.getTotal(),pageResult.getPageSize(),pageResult.getPageNo());
        }
        return PageResult.empty();
    }

    @Override
    public void remove(String hospCode, String hospScheduleId) {
        //根据医院编号 和 排班编号查询
        if (StringUtils.isAnyBlank(hospCode,hospScheduleId)){
            throw new ServiceException(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(),"医院编号和排班ID不能为空");
        }
        //根据医院编号和排班编号查询信息
        Schedule schedule = super.findOne(new Query(Criteria.where("hospCode").is(hospCode).and("hospScheduleId").is(hospScheduleId)));
        if(schedule != null) {
            super.deleteById(schedule.getId());
        }
    }

    @Override
    public Map<String, Object> getRuleSchedule(long page, long limit, String hospCode, String deptCode) {
        //1 根据医院编号 和 科室编号 查询
        Criteria criteria = Criteria.where("hospCode").is(hospCode).and("deptCode").is(deptCode);
        //分组查询总数
        long total = mongoTemplate.aggregate(Aggregation.newAggregation(Aggregation.match(criteria),
                        Aggregation.group("workDate")),
                Schedule.class, PreScheduleRuleRespDto.class).getMappedResults().size();
        Map<String, Object> result = new HashMap<>();
        if (total <= 0){
            result.put("total",0);
            return result;
        }
        // 根据工作日workDate期进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber"),
                Aggregation.sort(Sort.Direction.DESC,"workDate"),
                Aggregation.skip((page - 1) * limit),
                Aggregation.limit(limit)
        );
        List<PreScheduleRuleRespDto> mappedResults = mongoTemplate.aggregate(aggregation, Schedule.class, PreScheduleRuleRespDto.class)
                                                                  .getMappedResults();

        //把日期对应星期获取
        for(PreScheduleRuleRespDto respDto : mappedResults) {
            Date workDate = respDto.getWorkDate();
            String dayOfWeek = this.getDayOfWeek(workDate);
            respDto.setDayOfWeek(dayOfWeek);
        }

        //设置最终数据，进行返回
        result.put("bookingScheduleRuleList",mappedResults);
        result.put("total",total);

        //获取医院名称
        String hosName = hospitalService.getHospName(hospCode);
        //其他基础数据
        result.put("hospName",hosName);
        return null;
    }

    @Override
    public List<ScheduleRespDto> getDetailSchedule(String hospCode, String deptCode, String workDate) {
        //根据参数查询mongodb
        Schedule querySchedule = new Schedule();
        querySchedule.setHospCode(hospCode);
        querySchedule.setDeptCode(deptCode);
        querySchedule.setWorkDate(new DateTime(workDate).toJdkDate());
        List<Schedule> scheduleList = super.findByCondition(querySchedule);
        if (CollectionUtil.isNotEmpty(scheduleList)){
            //把得到list集合遍历，向设置其他值：医院名称、科室名称、日期对应星期
            List<ScheduleRespDto> collect = scheduleList.stream().map(item -> {
                ScheduleRespDto respDto = new ScheduleRespDto();
                BeanUtils.copyProperties(item, respDto);
                return respDto;
            }).collect(Collectors.toList());
            collect.forEach(item->{
                this.fillSchedule(item);
            });
            return collect;
        }
        return null;
    }

    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private ScheduleRespDto fillSchedule(ScheduleRespDto schedule) {
        //设置医院名称
        schedule.setHospName(hospitalService.getHospName(schedule.getHospName()));
        //设置科室名称
        schedule.setDeptName(departmentService.getDepName(schedule.getHospCode(),schedule.getDeptCode()));
        //设置日期对应星期
        String dayOfWeek = this.getDayOfWeek(schedule.getWorkDate());
        schedule.setDayOfWeek(dayOfWeek);
        return schedule;
    }

    //获取可预约分页数据
    private PageResult<Date> getListDate(int page, int limit, PreBookRule bookingRule) {
        //获取当天放号时间  年 月 日 小时 分钟
        Date date = new Date();
        DateTime releaseTime = this.getDateTime(date, bookingRule.getReleaseTime());
        //获取预约周期
        Integer cycle = bookingRule.getCycle() == null? 0: bookingRule.getCycle();
        //如果当天放号时间已经过去了，预约周期从后一天开始计算，周期+1
        if(releaseTime.isBefore(date)) {
            cycle += 1;
        }
        //获取可预约所有日期，最后一天显示即将放号
        List<Date> dateList = new ArrayList<>();
        for(int i = 0; i < cycle; i++) {
            Date curDateTime = DateUtils.addDate(date, Calendar.DAY_OF_MONTH, i);
            String dateString = new DateTime(curDateTime).toString("yyyy-MM-dd");
            dateList.add(DateUtil.parseDateTime(dateString).toJdkDate());
        }
        //因为预约周期不同的，每页显示日期最多7天数据，超过7天分页
        List<Date> pageDateList = new ArrayList<>();
        int start = (page-1)*limit;
        int end = (page-1)*limit+limit;
        //如果可以显示数据小于7，直接显示
        if(end > dateList.size()) {
            end = dateList.size();
        }
        for(int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        //如果可以显示数据大于7，进行分页
        return new PageResult<Date>(pageDateList, Long.parseLong(dateList.size()+""), limit, page);
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        return DateUtil.parse(dateTimeString, "yyyy-MM-dd HH:mm");
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hospCode, String deptCode) {
        Map<String,Object> result = new HashMap<>();
        //获取预约规则
        //根据医院编号获取预约规则
        HospitalRespDto respDto = hospitalService.getByHospCode(hospCode);
        if(respDto == null) {
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        PreBookRule bookingRule = respDto.getBookingRule();

        //获取可预约日期的数据（分页）
        PageResult<Date> pageResult = this.getListDate(page, limit, bookingRule);
        //当前可预约日期
        List<Date> dateList = pageResult.getList();

        //获取可预约日期里面科室的剩余预约数
        Criteria criteria = Criteria.where("hospCode").is(hospCode).and("deptCode").is(deptCode)
                .and("workDate").in(dateList);

        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate").first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<PreScheduleRuleRespDto> aggregateResult =
                mongoTemplate.aggregate(agg, Schedule.class, PreScheduleRuleRespDto.class);
        List<PreScheduleRuleRespDto> scheduleVoList = aggregateResult.getMappedResults();

        //合并数据  map集合 key日期  value预约规则和剩余数量等
        Map<Date, PreScheduleRuleRespDto> scheduleVoMap = new HashMap<>();
        if(CollectionUtil.isNotEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().
                    collect(
                            Collectors.toMap(PreScheduleRuleRespDto::getWorkDate,
                                    BookingScheduleRuleVo -> BookingScheduleRuleVo,
                                    (v1, v2) -> v2));
        }
        //获取可预约排班规则
        List<PreScheduleRuleRespDto> bookingScheduleRuleVoList = new ArrayList<>();
        Date curDate = new Date();
        for(int i=0; i < dateList.size(); i++) {
            Date date = dateList.get(i);
            //从map集合根据key日期获取value值
            PreScheduleRuleRespDto scheduleRuleDto = scheduleVoMap.get(date);
            //如果当天没有排班医生
            if(scheduleRuleDto == null) {
                scheduleRuleDto = new PreScheduleRuleRespDto();
                //就诊医生人数
                scheduleRuleDto.setDocCount(0);
                //科室剩余预约数  -1表示无号
                scheduleRuleDto.setAvailableNumber(-1);
            }
            scheduleRuleDto.setWorkDate(date);
            scheduleRuleDto.setWorkDateMd(date);
            //计算当前预约日期对应星期
            String dayOfWeek = this.getDayOfWeek(date);
            scheduleRuleDto.setDayOfWeek(dayOfWeek);

            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == dateList.size()-1 && page == pageResult.getTotalPages()) {
                scheduleRuleDto.setStatus(1);
            } else {
                scheduleRuleDto.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1) {
                DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
                if(stopTime.isBefore(curDate)) {
                    //停止预约
                    scheduleRuleDto.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(scheduleRuleDto);
        }

        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", pageResult.getTotal());

        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hospName", hospitalService.getHospName(hospCode));
        //科室
        DeptRespDto deptDto = departmentService.getDepartment(hospCode, deptCode);
        //大科室名称
        baseMap.put("bigName", deptDto.getBigName());
        //科室名称
        baseMap.put("deptName", deptDto.getDeptName());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap", baseMap);
        return result;
    }

    private String getDayOfWeek(Date date) {
       return Week.of(new DateTime(date).dayOfWeekInMonth()).toChinese();
    }

    @Override
    public ScheduleRespDto getScheduleId(String scheduleId) {
        Schedule schedule = super.findById(scheduleId);
        if (schedule != null) {
            ScheduleRespDto respDto = new ScheduleRespDto();
            BeanUtils.copyProperties(schedule, respDto);
            return this.fillSchedule(respDto);
        }
        return null;
    }

    @Override
    public ScheduleOrderRespDto getScheduleOrder(String scheduleId) {
        ScheduleOrderRespDto scheduleOrderVo = new ScheduleOrderRespDto();
        //获取排班信息
        Schedule schedule = super.findById(scheduleId);
        if(schedule == null) {
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        //获取预约规则信息
        HospitalRespDto hospDto = hospitalService.getByHospCode(schedule.getHospCode());
        if(hospDto == null) {
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        PreBookRule bookingRule = hospDto.getBookingRule();
        if(bookingRule == null) {
            throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }

        //把获取数据设置到scheduleOrderVo
        scheduleOrderVo.setHospCode(schedule.getHospCode());
        scheduleOrderVo.setHospName(hospitalService.getHospName(schedule.getHospCode()));
        scheduleOrderVo.setDeptCode(schedule.getDeptCode());
        scheduleOrderVo.setDeptName(departmentService.getDepName(schedule.getHospCode(), schedule.getDeptCode()));
        scheduleOrderVo.setHospScheduleId(schedule.getHospScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setDoctName(schedule.getDoctName());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(DateUtils.addDate(schedule.getWorkDate(), Calendar.DAY_OF_MONTH, quitDay), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toJdkDate());

        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(), bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toJdkDate());

        //预约截止时间
        DateTime endTime = this.getDateTime(DateUtils.addDate(schedule.getWorkDate(), Calendar.DAY_OF_MONTH, bookingRule.getCycle()), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toJdkDate());

        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(stopTime.toJdkDate());
        return scheduleOrderVo;
    }

    @Override
    public void update(ScheduleReqDto req) {
        Schedule schedule = null;
        if (StringUtils.isNotBlank(req.getId())) {
            schedule = super.findById(req.getId());
        } else if (StringUtils.isNotBlank(req.getHospScheduleId())) {
            schedule = super.findOne(new Query(Criteria.where("hospScheduleId").is(req.getHospScheduleId())));
        }
        if (schedule == null) {
           throw new ServiceException(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        Schedule entity = new Schedule();
        entity.setUpdateTime(new Date());
        super.updateById(schedule.getId(),entity);
    }
}
